package com.ruoyi.ws;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.*;

@Component
public class LogWebSocketHandler extends TextWebSocketHandler {
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    private final Map<WebSocketSession, ScheduledFuture<?>> sessionTasks = new ConcurrentHashMap<>();


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("Received: " + payload);
        session.sendMessage(new TextMessage("Echo: " + payload));
    }


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws IOException {



//        session.sendMessage(new TextMessage("Echo:afterConnectionEstablished "  ));
        session.sendMessage(new TextMessage("connected "  ));


        ScheduledFuture<?> task = scheduler.scheduleAtFixedRate(() -> {
            try {
                String logMessage = String.format("[%s] 系统日志信息",
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                session.sendMessage(new TextMessage(logMessage));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 0, 1, TimeUnit.SECONDS);

        sessionTasks.put(session, task);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        ScheduledFuture<?> task = sessionTasks.remove(session);
        if (task != null) {
            task.cancel(false);
        }
    }
}
